package com.kaifamiao.demo.d0811;

import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Iterator;

public class MyList2 extends AbstractCollection {

    // 内部容器
    private Object[] objs;

    // 元素的个数
    private int count;

    // 负载因子
    private float capacity;

    public MyList2(){
//        objs = new Object[10];
//        capacity = 0.8F;
        this(10);
    }

    public MyList2(int size){
        if (size >= 0){
            objs = new Object[size];
        }else{
            objs = new Object[10];
        }
        capacity = 0.8F;
    }

    public MyList2(Object[] objs){
        this.objs = objs;
        count = objs.length;
        capacity = 0.8F;
    }

    @Override
    public Iterator iterator() {
        return new MyList2Iterator();
    }

    private class MyList2Iterator implements Iterator {

        int index = -1;

        /**
         * 判断是否有下一个元素
         * @return
         */
        @Override
        public boolean hasNext() {
            return index < count - 1;
        }

        /**
         * 取下一个元素
         * @return
         */
        @Override
        public Object next() {
            if (hasNext()){
                return objs[++ index];
            }
            return null;
        }
    }

    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean add(Object o) {
        if (count >= objs.length * capacity) {
            // 扩容
            grow();
        }
        objs[count] = o;
        count ++;
        return true;
    }

    /**
     * 扩容
     */
    private void grow(){
        int oldSize = objs.length;
        // 1.5 倍
        int newSize = oldSize + (oldSize >> 1);
        // 将原来的元素复制到新的容器(数组)中
        objs = Arrays.copyOf(objs, newSize);
    }
}
